package com.lyf.core.dao;

import java.util.List;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import com.lyf.core.pojo.Menu;

@Repository
public interface MenuDao {
	
	@Insert("insert into ma_menu( menu_id,parent_id ,menu_name, menu_url, menu_icon, menu_type ,is_visible) "
			+ " values(#{m.menu_id},#{m.parent_id} ,#{m.menu_name}, #{m.menu_url},#{m.menu_icon},#{m.menu_type} ,#{m.is_visible})")
	public void insert(@Param("m") Menu m);
	
	@Insert("delete from ma_menu where menu_id = #{menu_id}")
	public void delete(@Param("menu_id") String menu_id);
	
	@Select("select * from ma_menu where menu_id=#{menu_id}")
	public Menu findById(@Param("menu_id") String menu_id);
	
	@Update("update ma_menu set  parent_id=#{m.parent_id},menu_name=#{m.menu_name}, menu_url=#{m.menu_url}, menu_icon=#{m.menu_icon}, menu_type =#{m.menu_type},is_visible=#{m.is_visible} where menu_id=#{m.menu_id}")
	public void update(@Param("m") Menu m);

	@Select("select * from ma_menu as t1 where menu_id in (select regexp_split_to_table(perms , ',') from ma_roles where role_id = #{role_id})  ")
	public List<Menu> findMenusByRole(@Param("role_id") int role_id);
	
	@Select( {"<script>",  
			  "select * from ma_menu where  menu_type=#{menu_type} " ,
				"<when test='onlyVisible != null and onlyVisible == true '> " ,
				"  and is_visible = #{onlyVisible} " ,
				"</when>" ,
			"</script>"
			})
	public List<Menu> findMenus(@Param("menu_type")int menu_type ,@Param("onlyVisible") boolean onlyVisible);
	
	
	@Select({"<script>",  
		" with t as (",
		  " select  regexp_split_to_table(perms , ',') as menu_id from ma_role where role_id in (select regexp_split_to_table(roles , ',')::int from ma_user where user_id = #{user_id} ) ",
		  ") " ,  
		"select * from ma_menu as t where is_visible=true " ,   
		"<when test='user_id != null  '> " ,
			" and menu_id in (select distinct t.menu_id from t) " ,
		 "</when>" ,
		"<when test='hasPerm == null or hasPerm == false '> " ,
		"  and menu_type = 1 " ,
		"</when>" ,
		 
		"</script>"
	})
	public List<Menu> findMenusByUser(@Param("user_id") String user_id ,@Param("hasPerm")Boolean hasPerm);
	
	 
	
}
